package top.dark.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import top.dark.common.utils.R;
import top.dark.search.config.ElasticSearchConfig;
import top.dark.search.constant.EsConstant;
import top.dark.search.feign.ProductFeignService;
import top.dark.search.service.MallSearchService;
import top.dark.search.vo.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/3/11 15:49
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restClient;
    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 根据不同的条件查询商品信息
     */
    @Override
    public SearchResultVo search(SearchParamVo searchParamVo) {
        // 1、构建DSL查询参数
        SearchResultVo result = null;
        SearchRequest searchRequest = buildSearchRequest(searchParamVo);
        try {
            // 2、去ES查询数据
            SearchResponse resp = restClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 3、解析结果
            result = parseSearchResponse(resp,searchParamVo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）、排序、分页、高亮、聚合分析
     */
    private SearchRequest buildSearchRequest(SearchParamVo searchParamVo) {
        SearchRequest searchRequest = new SearchRequest(EsConstant.PRODUCT_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 1) 模糊匹配
        if (StringUtils.isNotEmpty(searchParamVo.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParamVo.getKeyword()));
        }
        // 2.1) 过滤，分类
        if (searchParamVo.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParamVo.getCatalog3Id()));
        }
        // 2.2) 过滤，品牌
        if (searchParamVo.getBrandId() != null && searchParamVo.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParamVo.getBrandId()));
        }
        // 2.3) 过滤，库存
        if (searchParamVo.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParamVo.getHasStock() == 1));
        }
        // 2.4) 过滤，价格区间，格式：12_4000、_6000、12_
        if (StringUtils.isNotEmpty(searchParamVo.getSkuPrice())) {
            String[] price = searchParamVo.getSkuPrice().split("_");
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            if (price.length == 2) {
                skuPrice.gte(price[0]);
                skuPrice.lte(price[1]);
            } else if (searchParamVo.getSkuPrice().startsWith("_")) {
                skuPrice.lte(price[0]);
            } else {
                skuPrice.gte(price[0]);
            }
            boolQueryBuilder.filter(skuPrice);
        }
        // 2.5) 过滤，属性，格式：attr=1_5寸:8寸&attrs=2_16G:8G
        if (searchParamVo.getAttrs() != null && searchParamVo.getAttrs().size() > 0) {
            for (String attr : searchParamVo.getAttrs()) {
                BoolQueryBuilder attrQuery = QueryBuilders.boolQuery();
                String[] str = attr.split("_");
                String attrId = str[0];
                attrQuery.filter(QueryBuilders.termQuery("attrs.attrId", attrId));
                String[] attrValues = str[1].split(":");
                attrQuery.filter(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs", attrQuery, ScoreMode.None));
            }
        }
        // 3) 排序，格式：skuPrice_asc/desc
        if (StringUtils.isNotEmpty(searchParamVo.getSort())) {
            String[] sort = searchParamVo.getSort().split("_");
            searchSourceBuilder.sort(sort[0], sort[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }
        // 4) 分页
        searchSourceBuilder.from((searchParamVo.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 5) 高亮
        if (StringUtils.isNotEmpty(searchParamVo.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style=color:red>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        // 6) 聚合分析
        // TODO 6.1) 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brandName_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brandImg_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
        // TODO 6.2) 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalogName_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
        // TODO 6.3) 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrId_agg = AggregationBuilders.terms("attrId_agg").field("attrs.attrId").size(50);
        attrId_agg.subAggregation(AggregationBuilders.terms("attrName_agg").field("attrs.attrName").size(1));
        attrId_agg.subAggregation(AggregationBuilders.terms("attrValue_agg").field("attrs.attrValue").size(1));
        attr_agg.subAggregation(attrId_agg);
        searchSourceBuilder.aggregation(attr_agg);

        log.info("构造的QLS语句：{}", searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        return searchRequest;
    }

    private SearchResultVo parseSearchResponse(SearchResponse resp, SearchParamVo searchParamVo) {
        SearchResultVo result = new SearchResultVo();
        SearchHits respHits = resp.getHits();
        // 1) 封装商品信息
        SearchHit[] hits = respHits.getHits();
        if (hits != null && hits.length > 0) {
            List<SkuInfoUpEsVo> skuInfoUpEsVos = new ArrayList<>();
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();
                SkuInfoUpEsVo vo = JSON.parseObject(source, SkuInfoUpEsVo.class);
                // 如果带keyword字段，高亮设置
                if (StringUtils.isNotEmpty(searchParamVo.getKeyword())) {
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    vo.setSkuTitle(skuTitle);
                }
                skuInfoUpEsVos.add(vo);
            }
            result.setProducts(skuInfoUpEsVos);
        }

        // 2) 封装属性信息
        List<SearchResultVo.AttrVo> attrs = new ArrayList<>();
        ParsedNested attr_agg = resp.getAggregations().get("attr_agg");
        ParsedLongTerms attrId_agg = attr_agg.getAggregations().get("attrId_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attrId_agg.getBuckets();
        for (Terms.Bucket bucket : attrIdAggBuckets) {
            Long attrId = bucket.getKeyAsNumber().longValue();
            String attrName = ((ParsedStringTerms) bucket.getAggregations().
                    get("attrName_agg")).getBuckets().get(0).getKeyAsString();
            List<String> attrValues = ((ParsedStringTerms)bucket.getAggregations().
                    get("attrValue_agg")).getBuckets().stream().
                    map(item ->item.getKeyAsString()).collect(Collectors.toList()) ;
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrs.add(attrVo);
        }
        result.setAttrs(attrs);
        // 3) 封装品牌信息
        List<SearchResultVo.BrandVo> brands = new ArrayList<>();
        ParsedLongTerms brand_agg = resp.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket bucket : brandAggBuckets) {
            Long brandId = bucket.getKeyAsNumber().longValue();
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brandName_agg")).getBuckets().get(0).getKeyAsString();
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brandImg_agg")).getBuckets().get(0).getKeyAsString();
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brands.add(brandVo);
        }
        result.setBrands(brands);
        // 4) 封装分类信息
        List<SearchResultVo.CatalogVo> catalogs = new ArrayList<>();
        ParsedLongTerms catalog_agg = resp.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalogAggBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : catalogAggBuckets) {
            Long catalogId = Long.parseLong(bucket.getKeyAsString());
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().
                    get("catalogName_agg")).getBuckets().get(0).getKeyAsString();
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogs.add(catalogVo);
        }
        result.setCatalogs(catalogs);
        // 5) 封装分页信息
        long total = respHits.getTotalHits().value;
        result.setPageNum(searchParamVo.getPageNum());
        result.setTotal(total);
        result.setTotalPages(total%EsConstant.PRODUCT_PAGESIZE == 0
                ?(int)total/EsConstant.PRODUCT_PAGESIZE:(int)(total/EsConstant.PRODUCT_PAGESIZE+1));
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= result.getTotalPages(); i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        // 6.1) 封装面包屑导航 - 属性
        if (searchParamVo.getAttrs() != null && searchParamVo.getAttrs().size() > 0) {
            List<Long> attrIds = new ArrayList<>();
            List<SearchResultVo.NavVo> navs = searchParamVo.getAttrs().stream().map(item -> {
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                // attr=1_5寸:8寸&attrs=2_16G:8G
                String[] str = item.split("_");
                navVo.setNavValue(str[1]);
                attrIds.add(Long.parseLong(str[0]));
                // TODO 调用商品服务获取属性信息
                R<AttrRespVo> info = productFeignService.info(Long.parseLong(str[0]));
                if (info != null && info.getCode() == 0) {
                    AttrRespVo attrRespVo = info.getData("attr",new TypeReference<AttrRespVo>(){});
                    if (attrRespVo != null) {
                        navVo.setNavName(attrRespVo.getAttrName());
                    }
                } else {
                    navVo.setNavName(str[0]);
                }
                String replaceStr = getQueryString(searchParamVo, item, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replaceStr);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navs);
            result.setAttrIds(attrIds);
        }
        // 6.2) 封装面包屑导航 - 品牌
        List<SearchResultVo.NavVo> navs = result.getNavs();
        if (searchParamVo.getBrandId() != null && searchParamVo.getBrandId().size() > 0) {
            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
            navVo.setNavName("品牌");
            // TODO 调用商品服务获取品牌信息
            R<List<BrandVo>> info = productFeignService.brandInfoByIds(searchParamVo.getBrandId());
            if (info != null && info.getCode() == 0) {
                List<BrandVo> brandVos = info.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuilder sb = new StringBuilder();
                String replaceStr = "";
                for (BrandVo vo : brandVos) {
                    sb.append(vo.getName()).append("、");
                    replaceStr = getQueryString(searchParamVo, vo.getBrandId()+"", "brandId");
                }
                if (sb.lastIndexOf("、") != -1) {
                    navVo.setNavValue(sb.substring(0, sb.lastIndexOf("、")));
                } else {
                    navVo.setNavValue(sb.toString());
                }
                navVo.setLink("http://search.gulimall.com/list.html?" + replaceStr);
                navs.add(navVo);
            }
        }
        return result;
    }

    private String getQueryString(SearchParamVo searchParamVo, String value,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String str = key + "=" + encode;
        return searchParamVo.get_queryString().replace(str, "").replace("&" + str,"");
    }


}
